import React, { useRef, useEffect, useState } from 'react';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
import {
  Card,
  Row,
  Col,
  Typography,
  Space,
  Tag,
  Progress,
  Divider,
  Timeline,
  Descriptions,
  Statistic,
  Alert,
} from 'antd';
import {
  UserOutlined,
  DashboardOutlined,
  BookOutlined,
  SecurityScanOutlined,
  BarChartOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  WarningOutlined,
  InfoCircleOutlined,
  RiseOutlined,
  FallOutlined,
  ClockCircleOutlined,
  TeamOutlined,
  TrophyOutlined,
  FireOutlined,
  StarOutlined,
  BulbOutlined,
  RobotOutlined,
  CalendarOutlined,
} from '@ant-design/icons';
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
  ArcElement,
  PointElement,
  LineElement,
  Filler,
} from 'chart.js';
import { Bar, Pie, Line, Doughnut } from 'react-chartjs-2';
import styled from 'styled-components';

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
  ArcElement,
  PointElement,
  LineElement,
  Filler
);

const { Title: AntTitle, Text, Paragraph } = Typography;

const ReportContainer = styled.div`
  background: white;
  padding: 40px;
  max-width: 1200px;
  margin: 0 auto;
  font-family: 'Microsoft YaHei', Arial, sans-serif;
  
  .report-header {
    text-align: center;
    margin-bottom: 40px;
    padding: 30px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border-radius: 12px;
  }
  
  .report-section {
    margin-bottom: 30px;
    padding: 20px;
    border: 1px solid #f0f0f0;
    border-radius: 8px;
    background: #fafafa;
  }
  
  .chart-container {
    margin: 20px 0;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  }
  
  .metric-card {
    text-align: center;
    padding: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0,0,0,0.1);
    margin-bottom: 20px;
  }
  
  .key-points {
    margin: 16px 0;
    padding: 16px;
    background: white;
    border-radius: 8px;
    border-left: 4px solid #52c41a;
  }
  
  .key-points ul {
    margin: 0;
    padding-left: 20px;
  }
  
  .key-points li {
    margin-bottom: 8px;
    display: flex;
    align-items: center;
  }
  
  .key-points li:before {
    content: "✓";
    color: #52c41a;
    font-weight: bold;
    margin-right: 8px;
  }
`;

interface PDFReportGeneratorProps {
  aiReport: any;
  onComplete: () => void;
}

const PDFReportGenerator: React.FC<PDFReportGeneratorProps> = ({ aiReport, onComplete }) => {
  const reportRef = useRef<HTMLDivElement>(null);
  const [isGenerating, setIsGenerating] = useState(false);

  // 用户增长数据
  const userGrowthData = {
    labels: ['1月', '2月', '3月', '4月', '5月', '6月', '7月'],
    datasets: [
      {
        label: '学生用户',
        data: [320, 380, 420, 450, 480, 520, 567],
        backgroundColor: 'rgba(54, 162, 235, 0.6)',
        borderColor: 'rgba(54, 162, 235, 1)',
        borderWidth: 2,
      },
      {
        label: '教师用户',
        data: [45, 52, 58, 62, 68, 72, 78],
        backgroundColor: 'rgba(255, 99, 132, 0.6)',
        borderColor: 'rgba(255, 99, 132, 1)',
        borderWidth: 2,
      },
    ],
  };

  // 系统性能数据
  const systemPerformanceData = {
    labels: ['CPU使用率', '内存使用率', '磁盘使用率', '网络带宽', '响应时间'],
    datasets: [
      {
        label: '当前值',
        data: [45, 62, 38, 75, 180],
        backgroundColor: [
          'rgba(54, 162, 235, 0.6)',
          'rgba(255, 99, 132, 0.6)',
          'rgba(255, 205, 86, 0.6)',
          'rgba(75, 192, 192, 0.6)',
          'rgba(153, 102, 255, 0.6)',
        ],
        borderColor: [
          'rgba(54, 162, 235, 1)',
          'rgba(255, 99, 132, 1)',
          'rgba(255, 205, 86, 1)',
          'rgba(75, 192, 192, 1)',
          'rgba(153, 102, 255, 1)',
        ],
        borderWidth: 2,
      },
    ],
  };

  // 课程分布数据
  const courseDistributionData = {
    labels: ['计算机科学', '数学', '物理', '化学', '生物', '其他'],
    datasets: [
      {
        data: [30, 25, 15, 12, 10, 8],
        backgroundColor: [
          '#FF6384',
          '#36A2EB',
          '#FFCE56',
          '#4BC0C0',
          '#9966FF',
          '#FF9F40',
        ],
        borderWidth: 2,
        borderColor: '#fff',
      },
    ],
  };

  // 用户活跃度趋势
  const userActivityData = {
    labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
    datasets: [
      {
        label: '日活跃用户',
        data: [450, 520, 480, 600, 580, 420, 380],
        fill: true,
        backgroundColor: 'rgba(54, 162, 235, 0.2)',
        borderColor: 'rgba(54, 162, 235, 1)',
        borderWidth: 2,
        tension: 0.4,
      },
    ],
  };

  const generatePDF = async () => {
    if (!reportRef.current) return;
    
    setIsGenerating(true);
    
    try {
      const canvas = await html2canvas(reportRef.current, {
        scale: 2,
        useCORS: true,
        allowTaint: true,
        backgroundColor: '#ffffff',
      });

      const imgData = canvas.toDataURL('image/png');
      const pdf = new jsPDF('p', 'mm', 'a4');
      
      const imgWidth = 210;
      const pageHeight = 295;
      const imgHeight = (canvas.height * imgWidth) / canvas.width;
      let heightLeft = imgHeight;

      let position = 0;

      pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;

      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        pdf.addPage();
        pdf.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
      }

      const fileName = `AI教学平台分析报告_${new Date().toISOString().slice(0, 10)}_${Date.now()}.pdf`;
      pdf.save(fileName);
      
      onComplete();
    } catch (error) {
      console.error('PDF生成失败:', error);
    } finally {
      setIsGenerating(false);
    }
  };

  useEffect(() => {
    if (aiReport) {
      generatePDF();
    }
  }, [aiReport]);

  if (!aiReport) return null;

  return (
    <div style={{ position: 'fixed', left: '-9999px', top: '-9999px' }}>
      <ReportContainer ref={reportRef}>
        {/* 报告头部 */}
        <div className="report-header">
          <AntTitle level={1} style={{ color: 'white', marginBottom: 16 }}>
            <RobotOutlined style={{ marginRight: 12 }} />
            {aiReport.title}
          </AntTitle>
          <Paragraph style={{ color: 'white', fontSize: '16px', marginBottom: 8 }}>
            基于AI深度学习的智能分析报告
          </Paragraph>
          <Space size="large">
            <Text style={{ color: 'white' }}>
              <ClockCircleOutlined /> 生成时间：{aiReport.generatedAt.toLocaleString()}
            </Text>
            <Text style={{ color: 'white' }}>
              <CalendarOutlined /> 分析周期：{aiReport.timeRange}
            </Text>
            <Tag color="blue" style={{ fontSize: '14px' }}>
              整体评分：{aiReport.overallScore}/100
            </Tag>
          </Space>
        </div>

        {/* 执行摘要 */}
        <div className="report-section">
          <AntTitle level={2}>
            <InfoCircleOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            执行摘要
          </AntTitle>
          <Paragraph style={{ fontSize: '16px', lineHeight: '1.8' }}>
            {aiReport.summary}
          </Paragraph>
          
          <Row gutter={[16, 16]} style={{ marginTop: 20 }}>
            <Col span={6}>
              <div className="metric-card">
                <Statistic
                  title="用户总数"
                  value={810}
                  prefix={<TeamOutlined />}
                  valueStyle={{ color: '#1890ff' }}
                />
                <Text type="secondary">较上月增长 12.5%</Text>
              </div>
            </Col>
            <Col span={6}>
              <div className="metric-card">
                <Statistic
                  title="活跃用户"
                  value={567}
                  prefix={<UserOutlined />}
                  valueStyle={{ color: '#52c41a' }}
                />
                <Text type="secondary">较上月增长 8.3%</Text>
              </div>
            </Col>
            <Col span={6}>
              <div className="metric-card">
                <Statistic
                  title="课程总数"
                  value={45}
                  prefix={<BookOutlined />}
                  valueStyle={{ color: '#faad14' }}
                />
                <Text type="secondary">较上月增长 5.7%</Text>
              </div>
            </Col>
            <Col span={6}>
              <div className="metric-card">
                <Statistic
                  title="考试总数"
                  value={23}
                  prefix={<TrophyOutlined />}
                  valueStyle={{ color: '#722ed1' }}
                />
                <Text type="secondary">较上月增长 15.2%</Text>
              </div>
            </Col>
          </Row>
        </div>

        {/* 用户行为分析 */}
        <div className="report-section">
          <AntTitle level={2}>
            <UserOutlined style={{ marginRight: 8, color: '#52c41a' }} />
            用户行为分析
          </AntTitle>
          
          <Row gutter={[24, 24]}>
            <Col span={12}>
              <div className="chart-container">
                <AntTitle level={4}>用户增长趋势</AntTitle>
                <Bar data={userGrowthData} />
              </div>
            </Col>
            <Col span={12}>
              <div className="chart-container">
                <AntTitle level={4}>用户活跃度趋势</AntTitle>
                <Line data={userActivityData} />
              </div>
            </Col>
          </Row>

          <div className="key-points">
            <Text strong>关键发现：</Text>
            <ul>
              {aiReport.sections[0]?.keyPoints?.map((point: string, index: number) => (
                <li key={index}>{point}</li>
              ))}
            </ul>
          </div>
        </div>

        {/* 系统性能分析 */}
        <div className="report-section">
          <AntTitle level={2}>
            <DashboardOutlined style={{ marginRight: 8, color: '#1890ff' }} />
            系统性能分析
          </AntTitle>
          
          <Row gutter={[24, 24]}>
            <Col span={12}>
              <div className="chart-container">
                <AntTitle level={4}>系统性能指标</AntTitle>
                <Bar data={systemPerformanceData} />
              </div>
            </Col>
            <Col span={12}>
              <div className="chart-container">
                <AntTitle level={4}>系统健康度</AntTitle>
                <Doughnut
                  data={{
                    labels: ['健康', '警告', '异常'],
                    datasets: [{
                      data: [96.5, 2.5, 1],
                      backgroundColor: ['#52c41a', '#faad14', '#ff4d4f'],
                    }]
                  }}
                />
              </div>
            </Col>
          </Row>

          <Descriptions title="系统状态详情" bordered style={{ marginTop: 20 }}>
            <Descriptions.Item label="响应时间">180ms</Descriptions.Item>
            <Descriptions.Item label="CPU使用率">45%</Descriptions.Item>
            <Descriptions.Item label="内存使用率">62%</Descriptions.Item>
            <Descriptions.Item label="磁盘使用率">38%</Descriptions.Item>
            <Descriptions.Item label="网络带宽">75%</Descriptions.Item>
            <Descriptions.Item label="系统健康度">96.5%</Descriptions.Item>
          </Descriptions>
        </div>

        {/* 课程学习分析 */}
        <div className="report-section">
          <AntTitle level={2}>
            <BookOutlined style={{ marginRight: 8, color: '#faad14' }} />
            课程学习分析
          </AntTitle>
          
          <Row gutter={[24, 24]}>
            <Col span={12}>
              <div className="chart-container">
                <AntTitle level={4}>课程类别分布</AntTitle>
                <Pie data={courseDistributionData} />
              </div>
            </Col>
            <Col span={12}>
              <div className="chart-container">
                <AntTitle level={4}>学习效果评估</AntTitle>
                <Progress
                  type="circle"
                  percent={72.8}
                  format={(percent) => `${percent}%`}
                  strokeColor="#52c41a"
                  size={120}
                />
                <div style={{ textAlign: 'center', marginTop: 16 }}>
                  <Text strong>课程完成率</Text>
                </div>
              </div>
            </Col>
          </Row>

          <Row gutter={[16, 16]} style={{ marginTop: 20 }}>
            <Col span={8}>
              <Card size="small">
                <Statistic
                  title="平均课程评分"
                  value={4.6}
                  suffix="/5.0"
                  valueStyle={{ color: '#faad14' }}
                />
              </Card>
            </Col>
            <Col span={8}>
              <Card size="small">
                <Statistic
                  title="热门课程参与度"
                  value={89}
                  suffix="%"
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
            <Col span={8}>
              <Card size="small">
                <Statistic
                  title="学习进度跟踪"
                  value={100}
                  suffix="%"
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
          </Row>
        </div>

        {/* 安全风险评估 */}
        <div className="report-section">
          <AntTitle level={2}>
            <SecurityScanOutlined style={{ marginRight: 8, color: '#722ed1' }} />
            安全风险评估
          </AntTitle>
          
          <Row gutter={[24, 24]}>
            <Col span={12}>
              <Alert
                message="安全状况良好"
                description="系统整体安全状况良好，未发现重大安全漏洞。用户数据加密完善，访问控制机制有效。"
                type="success"
                showIcon
                style={{ marginBottom: 16 }}
              />
              
              <div className="key-points">
                <Text strong>安全指标详情：</Text>
                <ul>
                  {aiReport.sections[3]?.keyPoints?.map((point: string, index: number) => (
                    <li key={index}>{point}</li>
                  ))}
                </ul>
              </div>
            </Col>
            <Col span={12}>
              <Card title="安全评分" size="small">
                <Progress
                  type="circle"
                  percent={85}
                  format={(percent) => `${percent}分`}
                  strokeColor="#52c41a"
                  size={100}
                />
                <div style={{ textAlign: 'center', marginTop: 16 }}>
                  <Text type="secondary">安全等级：优秀</Text>
                </div>
              </Card>
            </Col>
          </Row>
        </div>

        {/* 数据趋势预测 */}
        <div className="report-section">
          <AntTitle level={2}>
            <BarChartOutlined style={{ marginRight: 8, color: '#faad14' }} />
            数据趋势预测
          </AntTitle>
          
          <Alert
            message="趋势预测"
            description="基于历史数据分析，预计下月用户增长率为8-12%，系统负载将保持在安全范围内。建议提前扩容服务器资源。"
            type="warning"
            showIcon
            style={{ marginBottom: 20 }}
          />
          
          <Row gutter={[16, 16]}>
            <Col span={6}>
              <Card size="small">
                <Statistic
                  title="用户增长预测"
                  value="8-12"
                  suffix="%"
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small">
                <Statistic
                  title="系统负载预测"
                  value="稳定"
                  valueStyle={{ color: '#1890ff' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small">
                <Statistic
                  title="资源需求"
                  value="建议扩容"
                  valueStyle={{ color: '#faad14' }}
                />
              </Card>
            </Col>
            <Col span={6}>
              <Card size="small">
                <Statistic
                  title="风险等级"
                  value="低"
                  valueStyle={{ color: '#52c41a' }}
                />
              </Card>
            </Col>
          </Row>
        </div>

        {/* 建议措施 */}
        <div className="report-section">
          <AntTitle level={2}>
            <BulbOutlined style={{ marginRight: 8, color: '#faad14' }} />
            建议措施
          </AntTitle>
          
          <Timeline>
            {aiReport.recommendations.map((rec: string, index: number) => (
              <Timeline.Item
                key={index}
                color="blue"
              >
                <Text strong>{rec}</Text>
              </Timeline.Item>
            ))}
          </Timeline>
        </div>

        {/* 后续行动 */}
        <div className="report-section">
          <AntTitle level={2}>
            <CheckCircleOutlined style={{ marginRight: 8, color: '#52c41a' }} />
            后续行动
          </AntTitle>
          
          <Timeline>
            {aiReport.nextSteps.map((step: string, index: number) => (
              <Timeline.Item
                key={index}
                color="green"
              >
                <Text strong>{step}</Text>
              </Timeline.Item>
            ))}
          </Timeline>
        </div>

        {/* 报告尾部 */}
        <div style={{ textAlign: 'center', marginTop: 40, padding: '20px 0', borderTop: '1px solid #f0f0f0' }}>
          <Text type="secondary">
            本报告由智教质学AI教学平台自动生成，数据基于系统实时监控和历史数据分析。
          </Text>
          <br />
          <Text type="secondary">
            报告生成时间：{new Date().toLocaleString()} | 报告版本：v1.0
          </Text>
        </div>
      </ReportContainer>
    </div>
  );
};

export default PDFReportGenerator; 